/**
 *	---------------------------------------------------------------------------
 *	COMP 6231/FALL 2013
 *	Assignment - 02
 *	@author Talha Rahman (1296884)
 *	---------------------------------------------------------------------------
 *	This class processes each incoming UDP request to the server {@link StationServer}.
 *	This class extends the Thread class and runs concurrently - hence processing each
 *	UDP request in parallel. 
 *	  
 */
package ca.concordia.comp6231.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Arrays;
import java.util.List;

import ca.concordia.comp6231.frontend.FrontEnd;

public class UDPServiceRequestProcessor extends Thread {

	private FrontEnd frontEnd;
	private String responseString;
	private DatagramSocket socket;
	private DatagramPacket request;

	public UDPServiceRequestProcessor(FrontEnd corbaServer, DatagramSocket socket, DatagramPacket request) {
		this.frontEnd = corbaServer;
		this.socket = socket;
		this.request = request;
	}

	@Override
	public void run() {
		String requestString = new String(request.getData());
		System.out.println("The request string is : " + requestString);
		String testString1 = "getRecordCount";
		String testString2 = "transferRecord";
		
		if (requestString.startsWith(testString1)) {
			
		}else if(requestString.trim().startsWith(testString2)){
			List<String> items = Arrays.asList(requestString.trim().split("\\="));
			String recordString = "";
			if(items.size() > 0){
				recordString = items.get(1).replaceAll("\\{", "").replaceAll("\\}", "");
			}
			
		}else{
			responseString = "Invalid Request.";
		}

		DatagramPacket reply = new DatagramPacket(responseString.getBytes(),
				responseString.length(), request.getAddress(),
				request.getPort());

		try {
			socket.send(reply);
		} catch (SocketException e) {
			System.out.println("Socket error: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("IO error: " + e.getMessage());
		}
	}
	

	public String getResponseString() {
		return responseString;
	}

}
